unit filehelper;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, fgl;

type
  TFilenameList = specialize TFPGList<String>;

function CompareFileNames(const A, B: String): Integer;
function FillFilenameList(FolderPath: String): TFilenameList;

resourcestring
  NoneFilename = '(None)';
  TilesBFilename = '(Tiles B)';
  TilesCFilename = '(Tiles C)';
  TilesDFilename = '(Tiles D)';
  TilesEFilename = '(Tiles E)';

implementation

{ Comparison function that sorts names with ! and $ below other names }
function CompareFileNames(const A, B: String): Integer;
var
  ASpecial: Boolean = False; //< Whether A starts with ! or $
  BSpecial: Boolean = False; //< Whether A starts with ! or $
begin
  if Length(A) > 0 then
    ASpecial := (A[1] = '$') or (A[1] = '!');
  if Length(B) > 0 then
    BSpecial := (B[1] = '$') or (B[1] = '!');

  if ASpecial and not BSpecial then
    CompareFileNames := 1
  else if BSpecial and not ASpecial then
    CompareFileNames := -1
  else if B < A then
    CompareFileNames := 1
  else if B > A then
    CompareFileNames := -1
  else
    CompareFileNames := 0;
end;

function FillFilenameList(FolderPath: String): TFilenameList;
var
  FileNames: TFilenameList;
  Info: TSearchRec;
  WildcardsPath: String;
  NameWithoutExtension: String;
begin
  FileNames := TFilenameList.Create;
  WildcardsPath := FolderPath + DirectorySeparator + '*.png';
  if FindFirst(WildcardsPath, faAnyFile, Info) = 0 then
    repeat
      NameWithoutExtension := ChangeFileExt(Info.Name, '');
      FileNames.Add(NameWithoutExtension);
    until FindNext(Info) <> 0;
  FindClose(Info);

  FileNames.Sort(@CompareFileNames);

  FillFilenameList := FileNames
end;

end.

